#include "pelicanomonitorws.h"
#include "settings.h"
#include "cfgfile.h"
#include "currentstatus.h"

PelicanoMonitorWS::PelicanoMonitorWS()
{
    CFGFile cfg;
    QString protocol("http://");
    QString endpoint = protocol+cfg.getServerMonitorIP()+":"+QString::number(cfg.getServerMonitorPort())+cfg.getServerMonitorPath()+"index.php?r=WsMonitor/wsdl&ws=1";
    _endpoint = new char[endpoint.size()+1];
    strcpy(_endpoint,endpoint.toStdString().c_str());
    _user = cfg.getMonitorUser();
    _pass = cfg.getMonitorPass();
    _idDevice = cfg.getIdDevice();
}
PelicanoMonitorWS::~PelicanoMonitorWS()
{
    if(_endpoint!=NULL)
    {
        delete _endpoint;
        _endpoint = NULL;
    }
}

bool PelicanoMonitorWS::login()
{
    qDebug() << "PelicanoMonitorWS::login()";
    WsMonitorControllerBinding wss;
    wss.endpoint = _endpoint;
    soap_ssl_init();
    if (soap_ssl_client_context(wss.soap,
       SOAP_SSL_NO_AUTHENTICATION,
       NULL,
       NULL,
       NULL,
       NULL,
       NULL
    ))
    {
       soap_print_fault(wss.soap, stderr);
    }
    qDebug() << "wss.endpoint: "<<wss.endpoint;
    std::string token;
    std::string user = _user.toStdString();
    std::string pass = _pass.toStdString();
    int result = wss.ns6__login(user,pass,token);
    if(result==SOAP_OK)
    {
        _token = QString::fromStdString(token);
        qDebug() << "heartBeat() SOAP OK";
    }
    else
    {
        _token = "";
        qDebug() << "heartBeat() SOAP Error";
        return false;
    }
    return true;

}

bool PelicanoMonitorWS::heartBeat()
{
    qDebug() << "PelicanoMonitorWS::heartBeat()";
    bool response = false;
    if(this->login())
    {
        WsMonitorControllerBinding wss;
        wss.endpoint = _endpoint;
        soap_ssl_init();
        if (soap_ssl_client_context(wss.soap,
           SOAP_SSL_NO_AUTHENTICATION,
           NULL,
           NULL,
           NULL,
           NULL,
           NULL
        ))
        {
           soap_print_fault(wss.soap, stderr);
        }
        qDebug() << "wss.endpoint: "<<wss.endpoint;
        ns6__HeartBeat request;
        request.description = "heart beat ripper";
        request.Id_USCOREdevice = _idDevice.toStdString();
        CurrentStatus *cStatus = CurrentStatus::getInstance();
        request.Id_USCOREdevice_USCOREstate = QString::number(cStatus->getCurrentStatus()).toStdString();
        request.Id_USCOREdevice_USCOREtype = "1";
        //request.insert_USCOREdate;//empty

        int result = wss.ns6__setHeartBeat(_token.toStdString(),&request,response);
        if(result==SOAP_OK)
        {
            qDebug() << "heartBeat() SOAP OK";
        }
        else
        {
            qDebug() << "heartBeat() SOAP Error";
        }
    }
    else
    {
        qDebug() << "login failed";

    }
    return response;
}
